//
//  SLUserSeacherViewModel.m
//  StarLight
//
//  Created by 吴涛 on 16/6/10.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLUserSeacherViewModel.h"
#import "SLNetWork.h"



@interface SLUserSeacherViewModel ()

@property (nonatomic, strong) NSString *path;

@property (nonatomic, strong) NSNumber *page;

@property (nonatomic, strong) NSString *keyWord;

@end



@implementation SLUserSeacherViewModel


- (instancetype)init{
  if (self = [super init]) {
    [self addObservers];
  }
  return self;
}


- (void)addObservers{
  @weakify(self)
  
  [[RACObserve(self, page) filter:^BOOL(NSNumber *value) {
    return value != nil;
  }] subscribeNext:^(NSNumber *newPage) {
    @strongify(self)
    NSString *auth = [DEFAULTS objectForKey:loginInfo][@"auth_token"];
    NSString *url = [NSString stringWithFormat:@"%@/user/userquery?keyword=%@&auth_token=%@&page=%@",baseUrl,self.keyWord,auth,newPage];
    self.path = url;
  }];
  
  [[RACObserve(self, path) filter:^BOOL(NSString *value) {
    return value.length > 0;
  }] subscribeNext:^(NSString *newPath) {
    @strongify(self)
    NSMutableArray *oldarr = [NSMutableArray arrayWithCapacity:1];
    if (![self.page isEqualToNumber:@1]) {
      [oldarr addObjectsFromArray:self.userList];
    }
    
    [SLNetWork getDataWithRequest:newPath complete:^(id respond, NSError *error) {
      
      if (!error) {

        self.userList = [SLFriendModel mj_objectArrayWithKeyValuesArray:respond[@"data"]];
      }
      
    }];
  }];
}

- (void)searchWithKeyWord:(NSString *)keyWord page:(NSNumber *)page{
  
  NSString *utf8kw = [keyWord stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  self.keyWord = utf8kw;
  self.page = page;
}


- (void)next{
  self.page = @(self.page.integerValue +1);
}

- (void)first{
  self.page = @1;
}





@end
